package com.koomii.redismq.demo.conf;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.util.Pool;

import com.koomii.redismq.RedisUtil;

/**
 * @author lizongyue
 */
@Configuration
public class RedismqConfig extends CachingConfigurerSupport {
	
	@Autowired
	Environment env;
	
	@Bean(name="messageTrunktaskExecutor")
	public ThreadPoolTaskExecutor getMessageTrunktaskExecutor() {
		ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
		//线程池维护线程的最少数量
		threadPool.setCorePoolSize(100);
		//线程池维护线程所允许的空闲时间
		threadPool.setKeepAliveSeconds(30000);
		//线程池维护线程的最大数量
		threadPool.setMaxPoolSize(1000);
		//线程池所使用的缓冲队列
		threadPool.setQueueCapacity(1000);
		return threadPool;
	}

    @Bean
    public RedisUtil redisUtil() {
    		//最大连接数，如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个JEDIS实例，则此时pool的状态为exhausted(耗尽)。
    		int maxTotal = 10;
    		//控制一个pool最多有多少个状态为idle(空闲的)的JEDIS实例
    		int maxIdle = 10;
    		//控制一个pool最少有多少个状态为idle(空闲的)的JEDIS实例
    		int minIdle = 0;
    		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		String host = "127.0.0.1";
		int port = 6379;
		int timeout = 100000;
//		String password = "";
//		int database = 8;
    		JedisPool pool = new JedisPool(config, host, port, timeout, false);
    		
    		RedisUtil redisUtil = new RedisUtil(pool);
        return redisUtil;
    }
    
    public RedisUtil redisSentinelUtil() {
		//最大连接数，如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个JEDIS实例，则此时pool的状态为exhausted(耗尽)。
		int maxTotal = 10;
		//控制一个pool最多有多少个状态为idle(空闲的)的JEDIS实例
		int maxIdle = 10;
		//控制一个pool最少有多少个状态为idle(空闲的)的JEDIS实例
		int minIdle = 0;
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		String host = "127.0.0.1";
		int port = 6379;
		int timeout = 100000;
		String password = "li*9#&19Fe";
		int database = 8;
		String masterName = "master1";
		//sentinel模式使用sentinel连接池
		Set<String> sentinels = new HashSet<String>();  
		sentinels.add(host + ":" + port);
		Pool<Jedis> pool  = new JedisSentinelPool(masterName, sentinels, config, timeout, password, database);
		RedisUtil redisUtil = new RedisUtil(pool);
    return redisUtil;
}
}
